package loganalysis;
import java.awt.Color;
import java.text.SimpleDateFormat;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import org.jfree.data.time.Millisecond;
import java.io.*;
import java.util.*;
/**
 * An example of a time series chart.  For the most part, default settings are used, except that
 * the renderer is modified to show filled shapes (as well as lines) at each data point.
 *
 */
public class DualAxisDemo2 extends ApplicationFrame {

    /**
     * A demonstration application showing how to create a time series chart with dual axes.
     *
     * @param title  the frame title.
     */
    public DualAxisDemo2(final String title) {

        super(title);
        this.ScanData("wilde/graph.txt");
       System.out.println("Start Curration");
        this.Curration();
        // create a title...
        final String chartTitle = "Average Completion Time of Graph";
        final XYDataset dataset = createDataset1();

        final JFreeChart chart = ChartFactory.createTimeSeriesChart(
            chartTitle, 
            "Date", 
            "Average Time",
            dataset, 
            true, 
            true, 
            false
        );

  //      final StandardLegend legend = (StandardLegend) chart.getLegend();
    //    legend.setDisplaySeriesShapes(true);
        
        final XYPlot plot = chart.getXYPlot();
        final NumberAxis axis2 = new NumberAxis("Number Of Task");
        axis2.setAutoRangeIncludesZero(false);
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, createDataset2());
        plot.mapDatasetToRangeAxis(1, 1);
        final XYItemRenderer renderer = plot.getRenderer();
        renderer.setToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
        if (renderer instanceof StandardXYItemRenderer) {
            final StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer;
         //   rr.setPlotShapes(true);
            rr.setShapesFilled(true);
        }
        
        final StandardXYItemRenderer renderer2 = new StandardXYItemRenderer();
        renderer2.setSeriesPaint(0, Color.black);
      //  renderer2.setPlotShapes(true);
        renderer.setToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
        plot.setRenderer(1, renderer2);
        
        final DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
        
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);

    }

    /**
     * Creates a sample dataset.
     *
     * @return The dataset.
     */
    private static double averageExecTime;
    private static double avgMemory;
     private ArrayList<ArrayList<String>> intermediateData ;
    private XYDataset createDataset1() {

        final TimeSeries ts = new TimeSeries("Average Time",Millisecond.class );
        //final TimeSeries s1 = new TimeSeries("Random Data 1", Month.class);
       for (int i =0; i<intermediateData.size();i++)
    { 
       System.out.println("Row = "+i );
        ts.add(new Millisecond(new Date(Long.parseLong(intermediateData.get(i).get(0)))),Double.parseDouble(intermediateData.get(i).get(1)));
    }
       
       // s1.add(new Month(7, 2002), 132.8);

        final TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(ts);

        return dataset;

    }

    /**
     * Creates a sample dataset.
     *
     * @return The dataset.
     */
    private XYDataset createDataset2() {

       // final TimeSeries ts = new TimeSeries();
        final TimeSeries ts = new TimeSeries("Number Of Task", Millisecond.class);
        for (int i =0; i<intermediateData.size();i++)
    { 
         ts.add(new Millisecond(new Date(Long.parseLong(intermediateData.get(i).get(0)))),Double.parseDouble(intermediateData.get(i).get(7)));
    }

        final TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(ts);

        return dataset;

    }

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************
    
    /**
     * Starting point for the demonstration application.
     *
     * @param args  ignored.
     */
    public static void main(final String[] args) {

        final DualAxisDemo2 demo = new DualAxisDemo2("Log Analysis");
        //demo.ScanData("graph.txt");
        demo.pack();
        
        RefineryUtilities.centerFrameOnScreen(demo);
        demo.setVisible(true);

    }
  public void ScanData(String filePath)
       {
            String fullFilePath = filePath;
            String line ="";
            BufferedReader loadLogFile;
            //2D Array
         intermediateData = new ArrayList<ArrayList<String>>();
             //Create file object and read it 
            try {
            loadLogFile= new BufferedReader(new FileReader (fullFilePath));
                
            
        //Initialize Row and column counter
         int row = 0;
         int col = 0;
         //Nested Loops to read file 
         
         while( (line = loadLogFile.readLine())!=null)
         {
             Scanner scanLine = new Scanner(line);
             intermediateData.add(new ArrayList<String>());
             while(scanLine.hasNext())
             {
                 intermediateData.get(row).add(scanLine.next());
                 col++;
             }
             row++;
         }
         }
         catch(FileNotFoundException e)
         {
             System.err.println("Error in reading logs: "+e);
         }
      catch(IOException e)
                {
                    System.err.println("Error in finding log file: "+e);
                }
        // Tesing region 
//        Iterator list = intermediateData.iterator();
//        while(list.hasNext())
//        {
//            System.out.println(list.next());
//        } 
       } 

public void Curration()
    {
        
       int cured =0;
       int k = intermediateData.size();
       ArrayList<String> remove;
       for (int i =0;i<k;i++)
       {    
          //System.out.println("Row is "+ i);
         //  System.out.println(logData.get(i));
             try{
               
               if(intermediateData.get(i).isEmpty())
                        {
                        //call code to curate the tmp file
                       System.out.println("Code is here");
                       
                      // cured++;
                        }
                   
                   }catch(IndexOutOfBoundsException e)
                   {
                       intermediateData.remove(i);
                   System.out.println("Error in line " + e);
                   System.out.println("Index of Row "+i);
                   intermediateData.remove(i);
                   cured++;
                   }
       }
       System.out.println("Total Lines Cured "+cured);
    
    }

}